package com.sicau.socialpracticesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sicau.socialpracticesystem.entity.param.prize.PrizeQueryParam;
import com.sicau.socialpracticesystem.entity.po.Prize;
import com.sicau.socialpracticesystem.entity.vo.PageDataVO;
import com.sicau.socialpracticesystem.entity.vo.prize.PrizeVO;
import com.sicau.socialpracticesystem.mapper.PrizeMapper;
import com.sicau.socialpracticesystem.mapper.VOMapper;
import com.sicau.socialpracticesystem.service.PrizeService;
import com.sicau.socialpracticesystem.util.PageUtil;
import com.sicau.socialpracticesystem.util.QueryWrapperUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 奖品表 服务实现类
 * </p>
 *
 * @author sxt && ttxxi
 * @since 2021-04-26
 */
@Service
public class PrizeServiceImpl extends ServiceImpl<PrizeMapper, Prize> implements PrizeService {

    /**
     * 排序属性
     */
    private static final String[] ORDER_COLUMN = {"id"};

    @Resource
    private VOMapper.PrizeVOMapper prizeVOMapper;

    @Resource
    private PrizeMapper prizeMapper;


    @Override
    public PageDataVO<PrizeVO> queryPrizeByConditions(PrizeQueryParam prizeQueryParam) {
        QueryWrapper<PrizeVO> queryWrapper = QueryWrapperUtil.getQueryWrapper(PrizeVO.class, PrizeQueryParam.class, prizeQueryParam);
        queryWrapper.orderByDesc(ORDER_COLUMN);
        Page<PrizeVO> infoVOPage = new Page<>(prizeQueryParam.getCurrentPage(), prizeQueryParam.getPageSize());
        infoVOPage = prizeVOMapper.selectPage(infoVOPage, queryWrapper);
        return PageUtil.convert(infoVOPage);
    }

    @Override
    public void updateNumberById(Integer id, Integer consumeNum) {
        Prize prize = prizeMapper.selectById(id);
        if ( (prize.getPrizeNumber() - prize.getExchangedNumber()) < consumeNum){
            throw new RuntimeException("更新prize异常,数量不够,id为"+ id +" 消耗分数为"+ consumeNum);
        }
        LambdaUpdateWrapper<Prize> updateWrapper = new LambdaUpdateWrapper<Prize>()
                .set(Prize::getExchangedNumber, prize.getExchangedNumber() + consumeNum)
                .eq(Prize::getId, id);
        prizeMapper.update(null, updateWrapper);
    }

    @Override
    public PrizeVO queryPrizeById(String id) {
        return prizeVOMapper.selectById(id);
    }
}
